package com.earl.gsm.web.system;

import java.util.List;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.hibernate.validator.constraints.NotEmpty;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import com.earl.gsm.commons.vo.DwzMessage;
import com.earl.gsm.commons.vo.ResultMessage;
import com.earl.gsm.domain.sercurity.role.Role;
import com.earl.gsm.domain.sercurity.user.User;
import com.earl.gsm.domain.sercurity.user.UserQuery;
import com.earl.gsm.security.shiro.ShiroPrincipal;
import com.earl.gsm.service.RoleService;
import com.earl.gsm.service.UserService;
import com.earl.gsm.web.BaseController;
import com.wordnik.swagger.annotations.ApiImplicitParam;
import com.wordnik.swagger.annotations.ApiImplicitParams;
import com.wordnik.swagger.annotations.ApiOperation;
import com.wordnik.swagger.annotations.ApiParam;

@RestController
@RequestMapping(value = "/system/user")
//@Api(value="Person Rest Service") //修改生成的son路径
public class UserController extends BaseController {

    private final Logger log = LoggerFactory.getLogger(UserController.class);

    @Autowired
    private UserService service;
    
    @Autowired
    private RoleService roleService;

    private ResultMessage result = null;

    /**
     * POST /users -> create a new user
     *
     * @RequestBody 专门处理非from表单数据，就是json,xml类型数据
     */
    @ApiOperation(value = "添加一个用户", notes = "ADD ONE USER", httpMethod = "POST", response = String.class)
    @RequestMapping(value = "/create", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "username", value = "User's name", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "realName", value = "User's email", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "phone", value = "User ID", required = true, dataType = "long", paramType = "query"),
            @ApiImplicitParam(name = "loginid", value = "User ID", required = true, dataType = "long", paramType = "query"),
            @ApiImplicitParam(name = "loginid", value = "User ID", required = true, dataType = "long", paramType = "query"),
            @ApiImplicitParam(name = "userImg", value = "User ID", required = true, dataType = "long", paramType = "query"),
            @ApiImplicitParam(name = "safePassword", value = "User ID", required = false, dataType = "long", paramType = "query")
    })
    public ResponseEntity<?> create(
            @ApiParam(required = false, name = "user", value = "这个字段不要理！！！！")
            @RequestParam(name = "userDto", required = false)
            User userDto) {
        result = new ResultMessage();
        UserQuery userQuery = new UserQuery();
                  userQuery.setUsername(userDto.getUsername());
        List<User> users = service.searchQuery(userQuery);
        if (!users.isEmpty()) {
            return ResponseEntity.badRequest()
                    .contentType(MediaType.TEXT_PLAIN)
                    .body("username already in use");
        }
        result.setServiceResult(service.saveUser(userDto));
        return new ResponseEntity<>(result, HttpStatus.CREATED);
    }

    /**
     * 根据id删除用户
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "删除一个用户", notes = "DELETE ONE USER", httpMethod = "DELETE", response = String.class)
    @RequestMapping(value = "/deleteById", method = RequestMethod.DELETE, produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<?> deleteById(
            @ApiParam(required = true, name = "id", value = "用户id")
            @RequestParam(name = "id", required = true)
            Long id) {
        service.delete(id);
        return new ResponseEntity<>(HttpStatus.OK);
    }

    @ApiOperation(value = "得到用户信息", notes = "user info", httpMethod = "GET", response = String.class)
    @RequestMapping(value = "/users/info", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<ShiroPrincipal> loginInfo2() {
        Subject subject = SecurityUtils.getSubject();

        //可以通过下面这个对象，动态修改用户权限信息
        ShiroPrincipal principal = (ShiroPrincipal) subject.getPrincipal();
        System.out.println(principal.toString());
        return new ResponseEntity<ShiroPrincipal>(principal, HttpStatus.OK);
    }

    @ApiOperation(value = "用户注册", notes = "user register system account ", httpMethod = "POST", response = String.class)
    @RequestMapping(value = "/register", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<ResultMessage> regitsterAccount(
            @ApiParam(required = true, name = "loginid", value = "用户登录账号")
            @NotEmpty(message = "注册账号不能为空")
            @RequestParam(name = "loginid", required = true)
            String loginid,
            @ApiParam(required = true, name = "password", value = "用户登录密码")
            @NotEmpty(message = "登录密码不能为空")
            @RequestParam(name = "password", required = true)
            String password) {
        service.save(new User(loginid, password));
        ResultMessage resultMessage = new ResultMessage();
        resultMessage.setResultInfo("注册成功");
        return new ResponseEntity<ResultMessage>(resultMessage, HttpStatus.OK);
    }
    
    
    /**
     * GET /users -> get all the users
     */
    @RequestMapping(value = "/all", method = RequestMethod.GET)
    @ApiOperation(value = "得到所有比赛简易信息", notes = "find All User", httpMethod = "GET", response = User.class, responseContainer = "List")
    public ModelAndView getAll() {
        log.debug("REST request to get all Users");
        return new ModelAndView("user/allUser","userList",service.findAll());
    }
    
    @RequestMapping(value = "/preAdd")
    public ModelAndView preAdd(){
    	
    	return new ModelAndView("user/addUser","roleList",roleService.findAll());
    }
    
    @RequestMapping(value = "/add")
    public ResponseEntity<DwzMessage> add(User user,Integer[] roleId){
    	service.addUserInfo(user,roleId);
    	DwzMessage dodo =new DwzMessage();
    	return new ResponseEntity<DwzMessage>(dodo,HttpStatus.OK);
    }
    
    @RequestMapping(value = "/preUpdate/{roleId}")
    public ModelAndView preUpdate(@PathVariable Long roleId){

    	return new ModelAndView("user/preUpdate","user",service.findOne(roleId)).addObject("roleList", roleService.findAll()).addObject("roleList2", service.findRole(roleId));
    }
    
    @RequestMapping(value = "/update")
    public ResponseEntity<DwzMessage> update(User user,Integer[] roleId){
    	
    	service.updateUserInfo(user,roleId);
    	
//    	service.updateByPrimaryKeySelective(role);
    	
    	DwzMessage dodo =new DwzMessage();
    	return new ResponseEntity<DwzMessage>(dodo,HttpStatus.OK);
    }
    
    @RequestMapping(value = "/delete/{roleId}")
    public ResponseEntity<DwzMessage> delete(@PathVariable Long roleId){
    	service.delete(roleId);
    	DwzMessage dwz = new DwzMessage();
    	return new ResponseEntity<DwzMessage>(dwz,HttpStatus.OK);
    }
}
